package com.itwxz.forum.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itwxz.forum.domain.po.ForumPostLike;
import com.itwxz.forum.service.ForumPostLikeService;
import com.itwxz.forum.mapper.ForumPostLikeMapper;
import com.itwxz.forum.service.ForumPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
* @author Admin
* @description 针对表【forum_post_like(帖子点赞表)】的数据库操作Service实现
* @createDate 2025-05-07 08:42:34
*/
@Service
public class ForumPostLikeServiceImpl extends ServiceImpl<ForumPostLikeMapper, ForumPostLike>
    implements ForumPostLikeService{

    @Autowired
    private ForumPostService postService;

    @Override
    public SaResult like(String postId) {
        Long userId = StpUtil.getLoginIdAsLong();

        LambdaQueryWrapper<ForumPostLike> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ForumPostLike::getPostId, postId);
        queryWrapper.eq(ForumPostLike::getUserId, userId);
        ForumPostLike like = getOne(queryWrapper);

        if (like == null) {
            like = new ForumPostLike();
            like.setPostId(Long.valueOf(postId));
            like.setUserId(userId);

            save(like);
            // 点赞数 +1
            postService.incrementLikeCount(postId);
            return SaResult.ok("点赞成功").setData(1);
        }else {
            removeById(like.getId());
            // 点赞数 -1
            postService.decrementLikeCount(postId);
            return SaResult.ok("已取消").setData(0);
        }
    }
}




